package com.lanyou.esb.cook.proxy.redis.proxy.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.exceptions.JedisException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.cook.proxy.common.Constants;
import com.lanyou.esb.cook.proxy.common.Constants4Redis;
import com.lanyou.esb.cook.proxy.entity.PfThroughput;
import com.lanyou.esb.cook.proxy.redis.JedisPoolUtils;
import com.lanyou.esb.cook.proxy.redis.proxy.base.BaseStrJedisProxy;

/**
 * 平台吞吐量Redis操作代理
 * 
 * @author Davey.wu
 */
public class PfThroughputJedisProxy extends BaseStrJedisProxy<PfThroughput> {
	/** 精确到日 **/
	private static final SimpleDateFormat DATEFORMATE = new SimpleDateFormat(
			Constants.DATE_PATTERN_YYYYMMDD_NOSPACE);

	public PfThroughputJedisProxy() {
		this.setTimeOut(Constants4Redis.REDIS_TIMEOUT_PF_THROUGHPUT);
		this.setPrefix(Constants4Redis.PREFIX_PFTHROUGHPUT);
	}

	@Override
	public long setex(String key, PfThroughput value) throws JedisException,
			JsonProcessingException {
		long result = 0;
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			String setResult = "";
			// 判断是否已经存在该对象，不存在则创建
			if (jedis.get(key) == null) {
				setResult = jedis.set(key, toJson(value));
				jedis.expire(key, this.getTimeOut());
			}
			// 区间吞吐量增加
			jedis.incrByFloat(getQytKey(key), value.getThroughputQty());
			jedis.expire(getQytKey(key), this.getTimeOut());
			if (STRING_SET_RESULT.equalsIgnoreCase(setResult)) {
				result = 1;
			}
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		return result;
	}

	/**
	 * 获取吞吐量
	 * 
	 * @param key
	 *            ：键
	 * @return
	 * @throws JedisException
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public double getQty(String key) throws JedisException, JsonParseException,
			JsonMappingException, IOException {
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			result = jedis.get(key);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		try {
			return Double.parseDouble(result);
		} catch (Exception e) {
			return 0.0;
		}

	}

	/**
	 * 获取吞吐量
	 * 
	 * @param keys
	 *            ：键集合
	 * @return
	 * @throws JedisException
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public Map<String, Double> getQty(List<String> keys) throws JedisException,
			JsonParseException, JsonMappingException, IOException {
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return null;
		}
		boolean broken = false;
		Map<String, Response<String>> responses = new HashMap<>(keys.size());
		try {
			Pipeline pipe = jedis.pipelined();
			for (String key : keys) {
				responses.put(key, pipe.get(key));
			}
			pipe.sync();
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (responses.isEmpty()) {
			return null;
		}
		Map<String, Double> result = new HashMap<>(responses.size());
		for (Entry<String, Response<String>> entry : responses.entrySet()) {
			double value = 0;
			try {
				value = Double.parseDouble(entry.getValue().get());
			} catch (Exception e) {
				value = 0;
			}
			result.put(entry.getKey(), value);
		}
		return result;
	}

	/**
	 * 值减少
	 * 
	 * @param map
	 *            ：键值对
	 * @throws JedisException
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public void decrByFloat(Map<String, Double> map) throws JedisException,
			JsonParseException, JsonMappingException, IOException {
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return;
		}
		boolean broken = false;
		try {
			Pipeline pipe = jedis.pipelined();
			for (Entry<String, Double> entry : map.entrySet()) {
				pipe.incrByFloat(entry.getKey(), -entry.getValue());
			}
			pipe.sync();
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
	}

	@Override
	public String getKeyFromObject(PfThroughput value) {
		return this.getPrefix() + KEY_SEPARATOR + value.getFieldId()
				+ KEY_SEPARATOR + DATEFORMATE.format(value.getStatisticsDate());
	}

	/**
	 * 获取吞吐量键
	 * 
	 * @param key
	 *            ：键
	 * @return
	 */
	public static String getQytKey(String key) {
		return key + Constants4Redis.SUFFIX_QTY;
	}
}
